/* eslint-disable */
require('script-loader!file-saver');

// require('script-loader!./Blob');
const { blob } = require('./Blob')
// require('script-loader!xlsx/dist/xlsx.core.min');
require('script-loader!xlsx-style/dist/xlsx.core.min')
function generateArray(table) {
    var out = [];
    var rows = table.querySelectorAll('tr');
    var ranges = [];
    for (var R = 0; R < rows.length; ++R) {
        var outRow = [];
        var row = rows[R];
        var columns = row.querySelectorAll('td');
        for (var C = 0; C < columns.length; ++C) {
            var cell = columns[C];
            var colspan = cell.getAttribute('colspan');
            var rowspan = cell.getAttribute('rowspan');
            var cellValue = cell.innerText;
            if (cellValue !== "" && cellValue == +cellValue) cellValue = +cellValue;

            //Skip ranges
            ranges.forEach(function (range) {
                if (R >= range.s.r && R <= range.e.r && outRow.length >= range.s.c && outRow.length <= range.e.c) {
                    for (var i = 0; i <= range.e.c - range.s.c; ++i) outRow.push(null);
                }
            });

            //Handle Row Span
            if (rowspan || colspan) {
                rowspan = rowspan || 1;
                colspan = colspan || 1;
                ranges.push({ s: { r: R, c: outRow.length }, e: { r: R + rowspan - 1, c: outRow.length + colspan - 1 } });
            }
            ;

            //Handle Value
            outRow.push(cellValue !== "" ? cellValue : null);

            //Handle Colspan
            if (colspan) for (var k = 0; k < colspan - 1; ++k) outRow.push(null);
        }
        out.push(outRow);
    }
    return [out, ranges];
};

function datenum(v, date1904) {
    if (date1904) v += 1462;
    var epoch = Date.parse(v);
    return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000);
}

function sheet_from_array_of_arrays(data, opts) {
    var ws = {};
    var range = { s: { c: 10000000, r: 10000000 }, e: { c: 0, r: 0 } };
    for (var R = 0; R != data.length; ++R) {
        for (var C = 0; C != data[R].length; ++C) {
            if (range.s.r > R) range.s.r = R;
            if (range.s.c > C) range.s.c = C;
            if (range.e.r < R) range.e.r = R;
            if (range.e.c < C) range.e.c = C;
            var cell = { v: data[R][C] };
            if (cell.v == null) continue;
            var cell_ref = XLSX.utils.encode_cell({ c: C, r: R });

            if (typeof cell.v === 'number') cell.t = 'n';
            else if (typeof cell.v === 'boolean') cell.t = 'b';
            else if (cell.v instanceof Date) {
                cell.t = 'n';
                cell.z = XLSX.SSF._table[14];
                cell.v = datenum(cell.v);
            }
            else cell.t = 's';
            cell.s = {
                border: {
                    top: { style: 'thin' },
                    bottom: { style: 'thin' },
                    left: { style: 'thin' },
                    right: { style: 'thin' }
                },
                alignment: { horizontal: "center", vertical: "center", wrap_text: true },
            }
            ws[cell_ref] = cell;
        }
    }
    if (range.s.c < 10000000) ws['!ref'] = XLSX.utils.encode_range(range);
    return ws;
}

function Workbook() {
    if (!(this instanceof Workbook)) return new Workbook();
    this.SheetNames = [];
    this.Sheets = {};
}

function s2ab(s) {
    var buf = new ArrayBuffer(s.length);
    var view = new Uint8Array(buf);
    for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
    return buf;
}

export function export_table_to_excel(id) {
    var theTable = document.getElementById(id);
    console.log('a')
    var oo = generateArray(theTable);
    var ranges = oo[1];

    /* original data */
    var data = oo[0];
    var ws_name = "SheetJS";
    console.log(data);

    var wb = new Workbook(), ws = sheet_from_array_of_arrays(data);

    /* add ranges to worksheet */
    // ws['!cols'] = ['apple', 'banan'];
    ws['!merges'] = ranges;

    /* add worksheet to workbook */
    wb.SheetNames.push(ws_name);
    wb.Sheets[ws_name] = ws;

    var wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: false, type: 'binary' });

    saveAs(new Blob([s2ab(wbout)], { type: "application/octet-stream" }), "test.xlsx")
}

function formatJson(jsonData) {
    console.log(jsonData)
}
export function export_json_to_excel(th, jsonData, defaultTitle) {
    var data = jsonData;
    data.unshift(th);
    var ws_name = "SheetJS";

    var wb = new Workbook(), ws = sheet_from_array_of_arrays(data);
    ws["A1"].s = {
        font: {
            name: '宋体',
            sz: 24,
            bold: true,
            color: { rgb: "000000" }
        },
        alignment: { horizontal: "center", vertical: "center", wrap_text: true },
    }
   
    //green back
    let green_arr = [];
    green_arr.forEach(function(item){
        ws[item].s.fill = {
            fgColor:{rgb: '00FF00'}
        }
    })
    //gray back
    let gray_arr = [];
    gray_arr.forEach(function(item){
        ws[item].s.fill = {
            fgColor:{rgb: 'C0C0C0'}
            //alignment: { horizontal: "center", vertical: "center", wrap_text: true },
        }
    })
    //左对齐
    let left_arr = ["A30","A29","A28","A27","A26","A24","B24","A23","B23","A22","B22","A21","B21","A20","B20",
    "A2","A7","A8","A9","A10","A11","A12","A13","A14","A15","A16","A17","A18","AA2"];
    left_arr.forEach(function(item){
        ws[item].s.alignment.horizontal = "left"
        //ws[item].s.alignment.horizontal = "center"
    })

    ws["!merges"] = [
        {  //标题
            s: {//s为开始
                c: 0,//开始列
                r: 0//开始取值范围
            },
            e: {//e结束
                c: 27,//结束列
                r: 0//结束范围
            }
        },
        {//单位
            s: {
                c: 0,
                r: 1
            },
            e: {
                c: 25,
                r: 1
            }
        },
        {//时间
            s: {
                c: 26,
                r: 1
            },
            e: {
                c: 27,
                r: 1
            }
        },
        {//分类
            s: {
                c: 0,
                r: 2
            },
            e: {
                c: 0,
                r: 3
            }
        },
        {//代码
            s: {
                c: 1,
                r: 2
            },
            e: {
                c: 1,
                r: 3
            }
        },
        {//合计
            s: {
                c: 2,
                r: 2
            },
            e: {
                c: 3,
                r: 2
            }
        },
        {//1:500
            s: {
                c: 4,
                r: 2
            },
            e: {
                c: 5,
                r: 2
            }
        },
        {//1:1000
            s: {
                c: 6,
                r: 2
            },
            e: {
                c: 7,
                r: 2
            }
        },
        {//1:2000
            s: {
                c: 8,
                r: 2
            },
            e: {
                c: 9,
                r: 2
            }
        },
        {//1:5000
            s: {
                c: 10,
                r: 2
            },
            e: {
                c: 11,
                r: 2
            }
        },
        {//1:10000
            s: {
                c: 12,
                r: 2
            },
            e: {
                c: 13,
                r: 2
            }
        },
        {//1:25000
            s: {
                c: 14,
                r: 2
            },
            e: {
                c: 15,
                r: 2
            }
        },
        {//1:50000
            s: {
                c: 16,
                r: 2
            },
            e: {
                c: 17,
                r: 2
            }
        },
        {//1:100000
            s: {
                c: 18,
                r: 2
            },
            e: {
                c: 19,
                r: 2
            }
        },
        {//1:250000
            s: {
                c: 20,
                r: 2
            },
            e: {
                c: 21,
                r: 2
            }
        },
        {//1:500000
            s: {
                c: 22,
                r: 2
            },
            e: {
                c: 23,
                r: 2
            }
        },
        {//1:1000000
            s: {
                c: 24,
                r: 2
            },
            e: {
                c: 25,
                r: 2
            }
        },
        {//其他
            s: {
                c: 26,
                r: 2
            },
            e: {
                c: 27,
                r: 2
            }
        },
        {//空白：
            s: {
                c: 0,
                r: 18
            },
            e: {
                c: 27,
                r: 18
            }
        },
        {//单位负责人
            s: {
                c: 1,
                r: 19
            },
            e: {
                c: 27,
                r: 19
            }
        },
        {//统计负责人
            s: {
                c: 1,
                r: 20
            },
            e: {
                c: 27,
                r: 20
            }
        },
        {//填报人
            s: {
                c: 1,
                r: 21
            },
            e: {
                c: 27,
                r: 21
            }
        },
        {//联系电话
            s: {
                c: 1,
                r: 22
            },
            e: {
                c: 27,
                r: 22
            }
        },
        {//报出日期
            s: {
                c: 1,
                r: 23
            },
            e: {
                c: 27,
                r: 23
            }
        },
        {//空白：
            s: {
                c: 0,
                r: 24
            },
            e: {
                c: 27,
                r: 24
            }
        },
        {//说明
            s: {
                c: 0,
                r: 25
            },
            e: {
                c: 27,
                r: 25
            }
        },
        {//1、填报单位XXXX
            s: {
                c: 0,
                r: 26
            },
            e: {
                c: 27,
                r: 26
            }
        },
        {//2、报告期别
            s: {
                c: 0,
                r: 27
            },
            e: {
                c: 27,
                r: 27
            }
        },
        {//3.表中的计量单位“幅”、“MB”统计累计提供的数据量。
            s: {
                c: 0,
                r: 28
            },
            e: {
                c: 27,
                r: 28
            }
        },
        {//4.逻辑关系：
            s: {
                c: 0,
                r: 29
            },
            e: {
                c: 27,
                r: 29
            }
        }
    ]
    ws["!cols"] = [
        { wch: 30 },
        { wch: 10 },
        { wch: 10 },
        { wch: 10 },
        { wch: 10 },
        { wch: 10 },
        { wch: 10 },
        { wch: 10 },
        { wch: 10 },
        { wch: 10 },
        { wch: 10 },
        { wch: 10 },
        { wch: 10 },
        { wch: 10 },
        { wch: 10 },
        { wch: 10 },
        { wch: 10 },
        { wch: 10 },
        { wch: 10 },
        { wch: 10 },
        { wch: 10 },
        { wch: 10 },
        { wch: 10 },
        { wch: 10 },
        { wch: 10 },
        { wch: 10 },
        { wch: 10 }
    ]
    wb.SheetNames.push(ws_name);
    wb.Sheets[ws_name] = ws;

    var wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: false, type: 'binary' });
    var title = defaultTitle || '列表'
    saveAs(new Blob([s2ab(wbout)], { type: "application/octet-stream" }), title + ".xlsx")
}
